import { login as loginApi } from '@/api/login'
import router from '@/router'
import { ElMessage } from 'element-plus'
export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    role: localStorage.getItem('role') || '',
    id: localStorage.getItem('id') || ''
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setRole(state, role) {
      state.role = role
      localStorage.setItem('role', role)
    },
    setId(state, id) {
      state.id = id
      localStorage.setItem('id', id)
    }
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginApi(userInfo)
          .then((res) => {
            console.log(res)
            if (res.data.code === 200) {
              ElMessage.success(res.data.msg)
              commit('setToken', res.data.data.token)
              commit('setRole', res.data.data.role)
              commit('setId', res.data.data.id)
              // setTokenTime()
              console.log(res.data)
              if (res.data.data.role === 3) {
                router.replace('/admin')
<<<<<<< HEAD
              } else if (res.data.data.role === 2) {
                router.replace('/captain')
              } else {
                router.replace('/student')
=======
              } else {
                router.replace('/captain')
>>>>>>> 7d520118954f103433f5074ad63a16f5b63acf51
              }
            } else {
              ElMessage.error(res.data.msg)
            }
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 退出
    logout({ commit }) {
      commit('setToken', '')
      commit('setId', '')
      commit('setRole', '')
      localStorage.clear()
      router.replace('/login')
    }
  }
}
